package zhcms.framework;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;

import zhcms.framework.dao.GyFor;
import zhcms.framework.dao.GyList;
import zhcms.framework.dao.GyPlus;

public class GyT {
	public String gytFile = "";
	//private String gytContent = "";
	private String gytFrontSeparator = "{";
	private String gytBackSeparator = "}";
	private String gytiCharset;
	private GyDaoContent gydContent;

	public String getGytiCharset() {
		return gytiCharset;
	}

	public void setGytiCharset(String gytiCharset) {
		this.gytiCharset = gytiCharset;
	}

	public HashMap<String, String> gytInVar;
	public HashMap<String, ArrayList<HashMap<String, String>>> gytInFor;
	public HashMap<String, String> gytInIf;

	public GyT() {
		gytInVar = new HashMap<String, String>(); // 变量
		gytInFor = new HashMap<String, ArrayList<HashMap<String, String>>>(); // 循环
		gytInIf = new HashMap<String, String>(); // 判断
		gydContent=new GyDaoContent();
	}

	public void setFrontSeparator(String gytemp) {
		this.gytFrontSeparator = gytemp;
	}

	public void setBackSeparator(String gytemp) {
		this.gytBackSeparator = gytemp;
	}

	public void setfilename(String gytfile) {
		this.gytFile = gytfile;
	}

	@SuppressWarnings("unused")
	private String getfilename() {
		return this.gytFile;
	}

	@SuppressWarnings("rawtypes")
	public HashMap setInVtrParameter(String ParameterName, String ParameterVale) {
		this.gytInVar.put(ParameterName, ParameterVale);
		return this.gytInVar;
	}

	@SuppressWarnings("rawtypes")
	public HashMap setInForParameter(String ParameterName,
			ArrayList<HashMap<String, String>> ParameterVale) {
		this.gytInFor.put(ParameterName, ParameterVale);
		return this.gytInFor;
	}

	@SuppressWarnings("rawtypes")
	public HashMap setInIfParameter(String ParameterName, String ParameterVale) {
		this.gytInIf.put(ParameterName, ParameterVale);
		return this.gytInIf;
	}

	private String readPath(String fileName)
	{
		String filePath = this.getClass().getResource("").getPath().toString();
		//System.out.println(filePath);
		
		if (filePath.indexOf("WEB-INF") > 0) {
			GySplit b = new GySplit();
			b.tool(filePath, "/WEB-INF");
			String[] temp_array = b.Show();
			b = null;
			filePath = temp_array[0];
		}

		filePath = filePath + "/" + fileName;
		
		//处理带file：//这种情况
		GyReplace r = new GyReplace();
		filePath = r.replace(filePath, "file:", "");
		r = null;
		
		return filePath;
	}
	
	private String readFile(String fileName) throws IOException {
		/*String filePath = this.getClass().getResource("").getPath().toString();
		System.out.println(filePath);
		
		if (filePath.indexOf("WEB-INF") > 0) {
			GySplit b = new GySplit();
			b.tool(filePath, "/WEB-INF");
			String[] temp_array = b.Show();
			b = null;
			filePath = temp_array[0];
		}

		filePath = filePath + "/" + fileName;
		
		//处理带file：//这种情况
		GyReplace r = new GyReplace();
		filePath = r.replace(filePath, "file:", "");
		r = null;*/
		
		
		String filePath=this.readPath(fileName);
		
		File f = new File(filePath);
		//String content = "";

        StringBuilder strContent = new StringBuilder("");
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(f)));
			String line = null;
			while ((line = br.readLine()) != null) {
				//lines.add(line);
                strContent.append(line.toString());
    			strContent.append("\n");
			}
			br.close();
		} catch (IOException e) {

		}

		return strContent.toString();
		//return content;
	}

	private String readFile(String fileName, String iCharset) throws IOException {
		/*String filePath = this.getClass().getResource("").getPath().toString();
		System.out.println(filePath);
		if (filePath.indexOf("WEB-INF") > 0) {
			GySplit b = new GySplit();
			b.tool(filePath, "/WEB-INF");
			String[] temp_array = b.Show();
			b = null;
			filePath = temp_array[0];
		}

		filePath = filePath + "/" + fileName;
		
		//处理带file：//这种情况
		GyReplace r = new GyReplace();
		filePath = r.replace(filePath, "file:", "");
		r = null;*/
		
		String filePath=this.readPath(fileName);
		
		File f = new File(filePath);
		//String mb_content = "";
		
		StringBuilder strContent = new StringBuilder("");
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), iCharset));
			String iline = null;
			while ((iline = br.readLine()) != null) {
				lines.add(iline.toString());
                strContent.append(iline.toString());
    			strContent.append("\n");
			}
			br.close();
		} catch (IOException e) {

		}
		

		return strContent.toString();
		//return mb_content;
	}

	public void parse(String iCharset) {
		try {
			
			//this.gytContent = readFile(this.gytFile, iCharset);
			gydContent.setContent(readFile(this.gytFile, iCharset));
			gytiCharset = iCharset;
			//System.out.println(this.gytContent);
			// 处理include标签
			RepInclude();
			// 处理判断
			RepIf();
			// this.gytContent=RepIf();
			// 处理list循环
			RepList();
			// 处理循环
			RepFor();
			
			// 处理插件
			RepPlus();
			
			// 处理替换的标签
			RepString();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void parse() {
		try {
			//this.gytContent = readFile(this.gytFile);
			gydContent.setContent(readFile(this.gytFile));
			// 处理include标签
			RepInclude();
			
			// 处理判断
			RepIf();
			
			// 处理list循环
			RepList();
			
			// 处理循环
			RepFor();
			
			// 处理插件
			RepPlus();
			
			// 处理替换的标签
			RepString();
			// this.gytContent=RepIf();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 包含文件
	private void RepInclude() throws IOException {
		String tempS = gydContent.getContent();
		//tempS = this.gytContent;
		String[] gytParameterArray = null;
		// 获取包含标签
		GySplit a = new GySplit();
		a.tool(tempS, this.gytFrontSeparator + "include=");
		String[] tempContent = a.Show();
		a = null;
		int temp_count = tempContent.length;
		if (temp_count == 0) {
			// 没有这个标签，跳过
		} else {
			gytParameterArray = new String[temp_count - 1];
			for (int i = 1; i < temp_count; i++) {
				GySplit b = new GySplit();
				b.tool(tempContent[i], this.gytBackSeparator);
				String[] temp_end_array = b.Show();
				b = null;
				gytParameterArray[i - 1] = temp_end_array[0];
			}
			
			// 对所有标签进行循环，提取include
			for (int i = 0; i < gytParameterArray.length; i++) {
				// String[] tempArray=this.gytParameterArray[i].split("=");
				String tempC = "";
				try {
					if (gytiCharset == null && gytiCharset.length() < 1) {
						tempC = readFile(gytParameterArray[i]);
					} else {
						tempC = readFile(gytParameterArray[i], gytiCharset);
					}
	
				} catch (IOException e) {
					e.printStackTrace();
				}
				// 使用自定义函数进行字符串替换
				GyReplace r = new GyReplace();
				tempS = r.replace(tempS, this.gytFrontSeparator + "include="
						+ gytParameterArray[i] + this.gytBackSeparator, tempC);
				r = null;
				// tempS=tempS.replaceAll(this.gytFrontSeparator+"include="+tempArray[1]+this.gytBackSeparator,
				// tempC);
			}
		}
		gydContent.setContent(tempS);
		//this.gytContent = tempS;
	}

	// 变量
	private void RepString() {
		String tempS = gydContent.getContent();
		//tempS = this.gytContent;
		List<String> gytParameterArray = new LinkedList<String>();
		// String[] gytParameterArray=null;
		// 获取变量标签
		GySplit a = new GySplit();
		a.tool(tempS, this.gytFrontSeparator);
		String[] tempContent = a.Show();
		a = null;
		int temp_count = tempContent.length;
		if (temp_count == 0) {
			// 没有这个标签，跳过
		} else {
			for (int i = 1; i < temp_count; i++) {
				GySplit b = new GySplit();
				b.tool(tempContent[i], this.gytBackSeparator);
				String[] temp_end_array = b.Show();
				b = null;
				if (temp_end_array[0].indexOf(".") >= 0) {
					// 存在.，即这个变量为循环中的变量，不替换
				} else {
					gytParameterArray.add(temp_end_array[0]);
				}
				// gytParameterArray[i-1] = temp_end_array[0];
			}
			for (int i = 0; i < gytParameterArray.size(); i++) {
				Iterator<Entry<String, String>> iSer = this.gytInVar.entrySet()
						.iterator();
				// System.out.println(gytParameterArray.get(i));
				while (iSer.hasNext()) {
					@SuppressWarnings("rawtypes")
					Map.Entry entry = (Map.Entry) iSer.next();
					// 查找是否存在，存在替换
					//System.out.println(gytParameterArray.get(i).toString());
					if (entry.getKey().toString().equals(gytParameterArray.get(i).toString())) {
						// 使用自定义函数进行字符串替换
						//System.out.println(entry.getKey().toString());
						GyReplace r = new GyReplace();
						tempS = r.replace(tempS, this.gytFrontSeparator + gytParameterArray.get(i) + this.gytBackSeparator, entry.getValue().toString());
						// tempS=tempS.replace(this.gytFrontSeparator+this.gytParameterArray[i]+this.gytBackSeparator,
						// this.gytParameterArray[i]);
						r = null;
					}
				}
			}
		}

		// 替换相应的变量
		//this.gytContent = tempS;
		gydContent.setContent(tempS);
	}
	
	//list标签，--新增
	private void RepList()
	{
		String tempS=gydContent.getContent();
			GyList gyl=new GyList();
			gyl.setContent(tempS);
			gyl.ParseList(this.gytFrontSeparator, this.gytBackSeparator);
			//this.gytContent=gyl.getreturnS();
			gydContent.setContent(gyl.getreturnS());
	}
	
	//list标签，--新增
	private void RepPlus()
	{
			String tempS=gydContent.getContent();
			GyPlus gyl=new GyPlus();
			gyl.setContent(tempS);
			gyl.ParsePlus(this.gytFrontSeparator, this.gytBackSeparator);
			//this.gytContent=gyl.getreturnS();
			gydContent.setContent(gyl.getreturnS());
	}
	
	// 循环
	private void RepFor() {
		String tempS=gydContent.getContent();
		//
		GyFor gyf=new GyFor();
		gyf.setContent(tempS);
		gyf.ParseFor(this.gytFrontSeparator, this.gytBackSeparator, gytInFor);
		//this.gytContent=gyf.getreturnS();
		gydContent.setContent(gyf.getreturnS());
	}

	private void RepIf() {
		String tempS=gydContent.getContent();
		String[] gytParameterArray = null;
		String[] gyitParameterArray = null;// 当前的if标签
		Vector<String> v = new Vector<String>();
		String[] tempContent = null;
		int temp_count = 0;

		GySplit h = new GySplit();
		h.tool(tempS, this.gytFrontSeparator);
		tempContent = h.Show();
		h = null;

		temp_count = tempContent.length;
		
		if(temp_count==0)
		{
			
		}
		else
		{
			gytParameterArray = new String[temp_count - 1];
			if (temp_count > 0) {
				// 得到标签
				for (int i = 1; i < temp_count; i++) {
					GySplit b = new GySplit();
					b.tool(tempContent[i], this.gytBackSeparator);
					String[] temp_end_array = b.Show();
					b = null;
					gytParameterArray[i - 1] = temp_end_array[0];
				}
			}
			for (int i = 0; i < gytParameterArray.length; i++) {
				if (gytParameterArray[i].substring(0, 3).toString().equals("if:")) {
					v.add(gytParameterArray[i]);
				}
			}

			if (v == null || v.size() == 0) {
				gydContent.setContent(tempS);
				//this.gytContent = tempS;
			} else {
				gyitParameterArray = new String[v.size()];

				for (int i = 0; i < gyitParameterArray.length; i++) {
					gyitParameterArray[i] = new String((String) v.elementAt(i));
				}
				v = null;

				// 循环的变量为gyitParameterArray[0]

				// String tempS="";
				String tempSpStart = "";// 循环前的字符串
				String tempSpEnd = "";// 循环后的字符串
				String tempSpIf = "";// 循环的字符串

				Iterator<Entry<String, String>> iSer = this.gytInIf.entrySet()
						.iterator();

				// 对for进行分割
				GySplit a = new GySplit();
				// System.out.println("1++"+"代码显示"+"<!--"+gyitParameterArray[0]+this.gytBackSeparator);
				a.tool(tempS, this.gytFrontSeparator + gyitParameterArray[0] + this.gytBackSeparator);
				String[] tempSIfHead = a.Show();
				a = null;
				// String[]
				// tempSIfHead=tempS.split("<!--"+this.gytParameterArray[i]+"-->");
				// System.out.println("222++"+"代码显示"+tempSIfHead[1]);
				// 得到要判断的变量和值
				GySplit f = new GySplit();
				f.tool(gyitParameterArray[0], " ");
				String[] tempParameterArray = f.Show();
				f = null;
				// System.out.println("变量值："+gyitParameterArray[0]);
				GySplit b = new GySplit();
				b.tool(tempSIfHead[1], this.gytFrontSeparator + "end" + tempParameterArray[0] + this.gytBackSeparator);
				String[] tempSIfEnd = b.Show();
				b = null;
				// System.out.println("1++"+"代码显示"+"<!--"+"end"+tempParameterArray[0]+"-->");
				// String[]
				// tempSIfEnd=tempS.split("<!--"+"end"+this.gytParameterArray[i]+"-->");
				tempSpStart = tempSIfHead[0];// 开始的 内容
				tempSpIf = tempSIfEnd[0];// 要判断的内容

				for (int af = 1; af < tempSIfEnd.length; af++) {
					tempSpEnd = tempSpEnd + this.gytFrontSeparator + "end" + tempParameterArray[0] + this.gytBackSeparator + tempSIfEnd[af];
				}

				// System.out.println("尾部代码显示3~~~~~\n"+tempSpEnd);
				String tempsub = this.gytFrontSeparator + "end" + tempParameterArray[0] + this.gytBackSeparator;

				tempSpEnd = tempSpEnd.substring(tempsub.length(),
						tempSpEnd.length());
				// tempSpEnd=tempSIfEnd[1];//结束的内容
				// System.out.println("尾部代码显示0~~~~~\n"+tempsub.length());
				// System.out.println("尾部代码显示1~~~~~\n"+tempSpEnd.length());
				// System.out.println("尾部代码显示2~~~~~\n"+tempSpEnd);
				tempSIfHead = null;
				tempSIfEnd = null;
				// 对判断体进行替换相关的内容，然后重新封装输出字符串
				// System.out.println("尾部代码显示"+tempSpEnd);
				// 得到要循环的list

				GySplit c = new GySplit();
				c.tool(tempParameterArray[0], ":");
				String[] tempIfParameterArray = c.Show();
				c = null;

				// System.out.println("1++"+"代码显示"+tempParameterArray[1]);
				while (iSer.hasNext()) {
					// 判断是否有没有输入的参数
					@SuppressWarnings("rawtypes")
					Map.Entry entry = (Map.Entry) iSer.next();
					// System.out.println("1++"+"代码显示"+entry.getKey().toString());
					// System.out.println("2++"+"代码显示"+tempIfParameterArray[1]);
					if (tempIfParameterArray[1].equals(entry.getKey().toString())) {
						// 找到输入的参数
						// 进行输处理
						// 得到要判断的变量的值
						String gytempA = entry.getValue().toString();

						String tempSS = "";
						// 对中间内容进行分割，然后替换
						if (tempSpIf.indexOf(this.gytFrontSeparator + "else:"
								+ tempIfParameterArray[1] + this.gytBackSeparator) > 0) {

							GySplit e = new GySplit();
							e.tool(tempSpIf, this.gytFrontSeparator + "else:"
									+ tempIfParameterArray[1] + this.gytBackSeparator);
							String[] tempSSIf = e.Show();
							e = null;
							// System.out.println("变量值0："+tempParameterArray.length);
							// System.out.println("变量值1："+tempParameterArray[1].toString());
							// System.out.println("变量值2："+gytempA);
							if (tempParameterArray[1].toString().equals(gytempA)) {
								tempSS = tempSSIf[0];
							} else {
								tempSS = tempSSIf[1];
							}
						} else {
							tempSS = tempSpIf;
						}
						// System.exit(0);
						gydContent.setContent(tempSpStart + tempSS + tempSpEnd);
						//this.gytContent = tempSpStart + tempSS + tempSpEnd;
						// System.out.println("全部代码显示"+this.gytContent);
						RepIf();
					}
				}
			}
		}
	}

	public String Out() {
		String tempS="";
		tempS=gydContent.getContent();
		//System.out.println("查看源代码：：");
		//System.out.println(tempS);
		return tempS;
	}

	public String test() {
		return "guoyong";
	}
}